package com.ly.algorithm.DataStructures.problem;

import java.util.Arrays;

/**
 * @Classname KnapsackProblem
 * @Description 动态规划-背包问题
 * @Date 2020/5/4 13:24
 * @Author 冷心影翼
 */
public class KnapsackProblem {

    public static void main(String[] args) {
        int[] w = {1,3,4};
        int[] value = {1500,2000,3000};
        int n = 5;
        int m = w.length;
        int[][] table = new int[m+1][n+1];
        int[][] path = new int[m+1][n+1];
        for (int i = 1; i <= m ; i++) {
            for (int j = 1; j <= n; j++) {
                if(w[i-1]>j) {
                    table[i][j] = table[i-1][j];
                }else {
                    int opt1 = table[i-1][j];
                    int opt2 = value[i-1]+table[i-1][j-w[i-1]];
                    if(opt2>opt1) {
                        table[i][j] = opt2;
                        path[i][j] = 1;
                    }else {
                        table[i][j] = opt1;
                    }
                }
            }
        }

        int i = m;
        int j = n;
        while (i>0 && j>0) {
            if(path[i][j] == 1) {
                System.out.println("第"+i+"个商品");
                j -= w[i-1];
            }
            i--;
        }

        for(int[] c: table) {
            System.out.println(Arrays.toString(c));
        }
    }

}
